/** 数值处理
 * @param number - 需要转换的数值
 * @param option - 配置选项
 **/
interface NhOption {
  unit?: string
  decimal?: number
  isRound?: boolean
  replace?: string
  type?: 'number' | 'currency'
  boundary?: boolean
  boundaryMax?: number
}
function canToNumber(number: number | string) {
  return !isNaN(Number(number)) && number !== null
}
export const numberHandle = (number: number | string, option: NhOption = {}): string => {
  const newOption: NhOption = {
    unit: option.unit || '',  // 单位
    decimal: (option.decimal || option.decimal === 0) ? option.decimal : -1,  // 保留小数位数，-1 不作处理
    isRound: option.isRound || false,  // 是否抹去小数尾部0
    replace: option.replace || '-',  // 不为数字形式时的占位文本
    type: option.type || 'number', // 数值输出形式，number - 常规数字 | currency - 欧式计数（100,000,000.00）
    boundary: option.boundary || false,  // 边界限制，true效果：0.001保留两位为0.01,0.999保留两位为0.99
    boundaryMax: option.boundaryMax || 1,  // 最大边界值 
  }

  if (canToNumber(number)) {
    const oldNumber = Number(number)
    let newNumber = String(number)

    if (option.decimal > -1) {
      newNumber = Number(newNumber).toFixed(newOption.decimal)

      if (option.boundary) {
        if (Number(newNumber) === 0 && oldNumber > 0) {
          newNumber = String(Number(newNumber.replace('.', '') + 1) / (10 ** option.decimal))
        } else if (Number(newNumber) === option.boundaryMax && oldNumber !== option.boundaryMax) {
          newNumber = String(Number(newNumber.replace('.', '') + 1) / (10 ** option.decimal))
        }
      }
    }

    if (newOption.isRound) {
      newNumber = String(parseFloat(newNumber))
    }

    if (newOption.type === 'currency') {
      newNumber = newNumber.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    }

    return newNumber + newOption.unit
  }

  return newOption.replace
}
